package com.itheima.controller;

import com.itheima.tool.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class UpLoadController {

    @Value("${reggie.path}")
    String path;

    @PostMapping("/upload")
    public R upload(MultipartFile file){


        String originalFilename = file.getOriginalFilename();
        String houzhui = originalFilename.substring(originalFilename.lastIndexOf("."));

        UUID uuid = UUID.randomUUID();

        String FileName= uuid +houzhui;
        File path = new File(this.path);

        System.out.println(path);
        if (!path.exists()){
            path.mkdirs();
        }
        try {
            file.transferTo(new File(this.path+FileName));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.success(FileName);
    }

    @GetMapping("download")
    public R DownLoad(String name, HttpServletResponse response){
        try {
            FileInputStream fis = new FileInputStream(this.path+name);
            ServletOutputStream os = response.getOutputStream();
            byte[] bytes = new byte[1024 * 8];
            int len;
            while((len=fis.read(bytes))!=-1){
                os.write(bytes,0,len);
                os.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success();
    }


}
